package com.cx.core.caffeine.config;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * Caffeine manager配置
 *
 * @author bmbfm
 * @date 2023-7-31 21:26:29
 */
@Component
public class CaffeineManagerConfig {
    @Resource
    private CaffeineConfig caffeineConfig;

    @Bean(name = "caffeine")
    public CacheManager initCacheManager(){
        CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
        Caffeine caffeine = Caffeine.newBuilder().initialCapacity(
                        Integer.parseInt(caffeineConfig.getInitCapacity()))
                .maximumSize(Integer.parseInt(caffeineConfig.getMaxSize()))
                .expireAfterAccess(Integer.parseInt(caffeineConfig.getExpireAfterAccess()),
                        TimeUnit.SECONDS);
        caffeineCacheManager.setCaffeine(caffeine);
        caffeineCacheManager.setCacheNames(StringUtils.isEmpty(caffeineConfig.getCacheNames()) ?
                new ArrayList<String>(){{
                    add("commCache");}}
                : Arrays.asList(caffeineConfig.getCacheNames().split(";")));
        caffeineCacheManager.setAllowNullValues(false);
        return caffeineCacheManager;
    }

    @Bean
    public CacheLoader<Object, Object> cacheLoader(){
        return new CacheLoader<Object, Object>() {
            @Override
            public  Object load(Object o) throws Exception {
                return null;
            }

            public Object reload(Object key, Object oldValue){
                // 重写这个方法将oldValue值返回，然后刷新缓存
                return oldValue;
            }
        };
    }
}
